import React, { Fragment } from 'react';
import {
  Card,
  Form,
  Input,
  Empty,
  Select,
  InputNumber,
  Button,
  Icon,
  Divider,
  Tooltip,
  Modal,
  Spin,
  message,
} from 'antd';
import { connect } from 'dva';
import { withPropsAPI } from 'gg-editor';
import upperFirst from 'lodash/upperFirst';
import cloneDeep from 'lodash/cloneDeep';
import ScrollBar from '@/components/ScrollBar';
import SelectForm from '../../../components/SelectForm';
import SelectMember from '../../../components/SelectMember';
import AddConfigRow from '../../../components/AddConfigRow';
import Flow2 from '@/pages/FormDesigner/templates/Flow2.js';
import styles from './index.less';

const { Item } = Form;
const namespace = 'flowConfig';

class DetailForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      result: [[], [], []],
      formState: false,
      memberState: false,
      memberCheck: [],
      configState: false,
      loading: false,
      formView: false,
    };
  }

  componentDidMount() {
    this.init();
  }

  /* eslint-disable */
  async init() {
    this.setState({
      loading: true,
    });
    await Promise.all([
      request('pmc/pms/StaticDataController/getStaticAttr.do', {
        data: {
          busiObjNbr: 'PmOrderFlowNode',
          attrNbr: 'operMode',
        },
      }),
      request('pmc/pms/StaticDataController/getStaticAttr.do', {
        data: {
          busiObjNbr: 'PmOrderFlowNode',
          attrNbr: 'isAuto',
        },
      }),
      request('pmc/pms/StaticDataController/getStaticAttr.do', {
        data: {
          busiObjNbr: 'PmOrderFlowDef',
          attrNbr: 'timeUnit',
        },
      }),
    ])
      .then(res => {
        if (res[0].success !== false && res[1].success !== false && res[2].success !== false) {
          this.setState({ result: res });
        }
      })
      .finally(() => {
        this.setState({
          loading: false,
        });
      });
  }
  /* eslint-enable  */

  get item() {
    const { propsAPI } = this.props;
    return propsAPI.getSelected()[0];
  }

  // node/edge 节点的数据保存
  handleSubmit = e => {
    if (e && e.preventDefault) {
      e.preventDefault();
    }
    const { form, propsAPI } = this.props;
    const { getSelected, executeCommand, update } = propsAPI;

    setTimeout(() => {
      form.validateFieldsAndScroll((err, values) => {
        if (err) {
          return;
        }
        // 若环节处理类型选择自动处理、接口服务则清空 “处理人模式”、“关联表单”，“环节处理人”的数据
        const cloneValues = values;
        if (values.isAuto === '0' || values.isAuto === '2') {
          cloneValues.operMode = undefined;
          cloneValues.objName = '';
          cloneValues.solveList = [];
          cloneValues.formName = '';
          cloneValues.formId = '';
        }
        // 若处理人模式为系统分配，环节处理人要改成单选
        if (values.operMode === '2') {
          // console.log(cloneValues.objName, cloneValues.solveList);
          if (cloneValues.solveList.length > 1) {
            const name = cloneValues.objName.substring(
              0,
              cloneValues.objName.indexOf(',') >= 0 ? cloneValues.objName.indexOf(',') : 0
            );
            const arr = cloneValues.solveList;
            arr.splice(1);
            cloneValues.objName = name;
            cloneValues.solveList = arr;
            this.props.form.setFieldsValue({
              solveList: arr,
              objName: name,
            });
          }
        }

        const item = getSelected()[0];
        if (!item) {
          return;
        }
        executeCommand(() => {
          update(item, {
            ...cloneValues,
          });
        });
      });
    }, 0);
  };

  // 在下拉选择时候需要宏观任务进行数据的更新
  handleModalSub = e => {
    if (e && e.preventDefault) {
      e.preventDefault();
    }
    const { form, propsAPI } = this.props;
    const { getSelected, executeCommand, update } = propsAPI;

    form.validateFieldsAndScroll((err, values) => {
      if (err) {
        return;
      }
      const item = getSelected()[0];
      if (!item) {
        return;
      }
      executeCommand(() => {
        update(item, {
          ...values,
        });
      });
    });
  };

  // 事件设置选择
  handleSubDataSource = dataSource => {
    const { propsAPI } = this.props;
    const { getSelected, executeCommand, update } = propsAPI;

    const item = getSelected()[0];
    if (!item) {
      return;
    }
    executeCommand(() => {
      update(item, {
        dataSource,
      });
    });
  };

  // 流程配置信息
  handleSubmitCanvas = e => {
    if (e && e.preventDefault) {
      e.preventDefault();
    }
    const { form } = this.props;
    setTimeout(() => {
      form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          const { dispatch } = this.props;
          dispatch({
            type: `${namespace}/saveCanvas`,
            payload: { ...values },
          });
        }
      });
    }, 0);
  };

  Addyunsuan = type => {
    const { form } = this.props;
    let paramsValue = form.getFieldValue('params');
    if (!paramsValue) {
      paramsValue = '';
    }
    form.setFieldsValue({ params: `${paramsValue}${type}` });
    this.handleSubmit();
  };

  createParams = () => {
    const { form } = this.props;
    const left = form.getFieldValue('left');
    const yunsuan = form.getFieldValue('yunsuan');
    const right = form.getFieldValue('right');
    const value = `{$${left}$${yunsuan}'${right}'}`;
    let paramsValue = form.getFieldValue('params');
    if (!paramsValue) {
      paramsValue = '';
    }
    form.setFieldsValue({ params: `${paramsValue}${value}` });
    this.handleSubmit();
  };

  formCallBack = value => {
    this.props.form.setFieldsValue({
      formId: value[0].formId,
      formName: value[0].formName,
    });
    this.handleModalSub();
  };

  memberCallBack = value => {
    const solveList = [];
    let objName = '';
    value.map(item => {
      solveList.push(item);
      objName = `${objName}${objName ? ',' : ''}${item.userName}`;
    });
    this.props.form.setFieldsValue({
      solveList,
      objName,
    });
    this.handleModalSub();
  };

  configCallBack = value => {
    const { dataSource } = this.item.getModel();
    const data = cloneDeep(dataSource);

    const result = data.some(item => {
      if (item.eventType === value.eventType) {
        return true;
      }
    });
    if (result) {
      Modal.confirm({
        content: `【${value.eventTypeName}】已经添加是否进行替换`,
        onOk() {
          // 删掉原先
          data.splice(
            data.findIndex(itt => itt.eventType === value.eventType),
            1
          );
          // 替换
          data.push({
            ...value,
          });
        },
      });
    } else {
      data.push({
        ...value,
      });
    }
    this.handleSubDataSource(data);
  };

  // 流程配置信息
  renderCanvasDetail = () => {
    const { form, canvasObj, operType } = this.props;
    return (
      <Form>
        <Form.Item label="流程名称">
          {form.getFieldDecorator('flowName', {
            initialValue: canvasObj.flowName,
          })(
            <Input
              placeholder="请输入"
              onBlur={this.handleSubmitCanvas}
              disabled={operType === 'view' ? true : false}
            />
          )}
        </Form.Item>
        <Form.Item label="流程编码">
          {form.getFieldDecorator('flowCode', {
            initialValue: canvasObj.flowCode,
          })(<Input placeholder="请输入" onBlur={this.handleSubmitCanvas} disabled />)}
        </Form.Item>
        <Form.Item label="流程版本">
          {form.getFieldDecorator('version', {
            initialValue: canvasObj.version,
          })(<Input placeholder="请输入" onBlur={this.handleSubmitCanvas} disabled />)}
        </Form.Item>
        <Form.Item label="完成时限">
          {form.getFieldDecorator('limitValue', {
            initialValue: canvasObj.limitValue,
          })(
            <InputNumber
              style={{ width: '100%' }}
              allowClear
              placeholder="请输入"
              onBlur={this.handleSubmitCanvas}
              disabled={operType === 'view' ? true : false}
            />
          )}
        </Form.Item>
        <Form.Item label="告警时限">
          {form.getFieldDecorator('alertValue', {
            initialValue: canvasObj.alertValue,
          })(
            <InputNumber
              style={{ width: '100%' }}
              allowClear
              placeholder="请输入"
              onBlur={this.handleSubmitCanvas}
              disabled={operType === 'view' ? true : false}
            />
          )}
        </Form.Item>
        <Form.Item label="时间单位">
          {form.getFieldDecorator('timeUnit', {
            initialValue: canvasObj.timeUnit,
          })(
            <Select
              allowClear
              placeholder="请选择"
              onChange={this.handleSubmitCanvas}
              disabled={operType === 'view' ? true : false}
            >
              {this.state.result[2].map(item => {
                return (
                  <Select.Option key={item.attrValue} value={item.attrValue}>
                    {item.attrValueName}
                  </Select.Option>
                );
              })}
            </Select>
          )}
        </Form.Item>
      </Form>
    );
  };

  // 流程环节
  renderNodeDetail = () => {
    const { form, operType } = this.props;
    const {
      shape,
      label,
      flowNodeCode,
      isAuto,
      operMode,
      objName,
      solveList,
      formName,
      formId,
      dataSource,
    } = this.item.getModel();

    return shape === 'flow-circle' ||
      shape === 'flow-rhombus' ||
      shape === 'flow-capsule' ||
      shape === 'custom-node' ||
      shape === 'custom-end' ? (
      <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="此节点暂无配置" />
    ) : (
      <Fragment>
        <Item label="环节名称">
          {form.getFieldDecorator('label', {
            initialValue: label,
          })(
            <Input
              onBlur={this.handleSubmit}
              placeholder="请输入"
              disabled={operType === 'view' ? true : false}
            />
          )}
        </Item>
        <Item label="环节编码">
          {form.getFieldDecorator('flowNodeCode', {
            initialValue: flowNodeCode,
          })(
            <Input
              onBlur={this.handleSubmit}
              placeholder="请输入"
              disabled={operType === 'view' ? true : false}
            />
          )}
        </Item>

        <Item label="环节处理类型">
          {form.getFieldDecorator('isAuto', {
            initialValue: isAuto,
          })(
            <Select
              onChange={this.handleSubmit}
              allowClear
              placeholder="请选择"
              disabled={operType === 'view' ? true : false}
            >
              {this.state.result[1].map(item => {
                return (
                  <Select.Option key={item.attrValue} value={item.attrValue}>
                    {item.attrValueName}
                  </Select.Option>
                );
              })}
            </Select>
          )}
        </Item>

        {form.getFieldValue('isAuto') === '0' || form.getFieldValue('isAuto') === '2' ? null : (
          <Fragment>
            <Item label="处理人模式">
              {form.getFieldDecorator('operMode', {
                initialValue: operMode,
              })(
                <Select
                  allowClear
                  placeholder="请选择"
                  onChange={this.handleSubmit}
                  disabled={operType === 'view' ? true : false}
                >
                  {this.state.result[0].map(item => {
                    return (
                      <Select.Option key={item.attrValue} value={item.attrValue}>
                        {item.attrValueName}
                      </Select.Option>
                    );
                  })}
                </Select>
              )}
            </Item>

            <Item label="环节处理人">
              {form.getFieldDecorator('objName', {
                initialValue: objName,
              })(
                <Input
                  readOnly
                  placeholder="请选择"
                  disabled={operType === 'view' ? true : false}
                  suffix={
                    operType !== 'view' ? (
                      <Fragment>
                        <Tooltip placement="top" title="选择">
                          <Icon
                            type="file-search"
                            onClick={() => {
                              this.setState({
                                memberState: true,
                                memberCheck: solveList,
                              });
                            }}
                          />
                        </Tooltip>
                      </Fragment>
                    ) : null
                  }
                />
              )}
            </Item>
            <Item label="solveList" hidden>
              {form.getFieldDecorator('solveList', {
                initialValue: solveList,
              })(<Input readOnly placeholder="请输入" />)}
            </Item>

            <Item label="表单名称">
              {form.getFieldDecorator('formName', {
                initialValue: formName,
              })(
                <Input
                  readOnly
                  disabled={operType === 'view' ? true : false}
                  placeholder="请选择"
                  className={styles.rest_input}
                  suffix={
                    <div>
                      {operType !== 'view' ? (
                        <Tooltip placement="top" title="选择">
                          <Icon
                            type="file-search"
                            onClick={() => {
                              this.setState({
                                formState: true,
                              });
                            }}
                          />
                        </Tooltip>
                      ) : null}
                      <Divider type="vertical" />
                      <Tooltip placement="top" title="预览">
                        <Icon
                          type="eye"
                          onClick={() => {
                            if (form.getFieldValue('formId')) {
                              this.setState({
                                formView: true,
                              });
                            } else {
                              message.info('请选择表单名称进行预览');
                            }
                          }}
                        />
                      </Tooltip>
                    </div>
                  }
                />
              )}
            </Item>
            <Item label="表单Id" hidden>
              {form.getFieldDecorator('formId', {
                initialValue: formId,
              })(<Input readOnly placeholder="请输入" />)}
            </Item>
          </Fragment>
        )}

        {operType !== 'view' ? (
          <Item>
            <a
              onClick={() => {
                this.setState({
                  configState: true,
                });
              }}
            >
              + 事件设置选择
            </a>
          </Item>
        ) : null}

        <Fragment>
          {dataSource.map(item => {
            return (
              <Item>
                <span style={{ color: 'rgba(0, 0, 0, 0.85)' }}>{item.eventTypeName} : </span>
                <Input
                  readOnly
                  disabled={operType === 'view' ? true : false}
                  value={item.planName}
                  suffix={
                    operType !== 'view' ? (
                      <Fragment>
                        <Tooltip placement="top" title="删除">
                          <Icon
                            type="delete"
                            onClick={e => {
                              const arr = cloneDeep(dataSource);
                              arr.splice(
                                arr.findIndex(itt => itt.eventType === item.eventType),
                                1
                              );
                              this.handleSubDataSource(arr);
                              this.setState({ memberState: false });
                            }}
                          />
                        </Tooltip>
                      </Fragment>
                    ) : null
                  }
                />
              </Item>
            );
          })}
        </Fragment>
      </Fragment>
    );
  };

  // 节点跃迁
  renderEdgeDetail = () => {
    const { form, operType } = this.props;
    const { label, params, pathType } = this.item.getModel();

    return (
      <Fragment>
        <Item label="条件名称">
          {form.getFieldDecorator('label', {
            initialValue: label,
          })(
            <Input
              onBlur={this.handleSubmit}
              placeholder="请输入"
              disabled={operType === 'view' ? true : false}
            />
          )}
        </Item>
        <Item label="正反向流程">
          {form.getFieldDecorator('pathType', {
            initialValue: pathType,
          })(
            <Select
              allowClear
              placeholder="请选择"
              onChange={this.handleSubmit}
              disabled={operType === 'view' ? true : false}
            >
              <Select.Option value="1">正向</Select.Option>
              <Select.Option value="2">反向</Select.Option>
            </Select>
          )}
        </Item>
        {operType !== 'view' ? (
          <Fragment>
            <Form.Item label="左表达式">
              {form.getFieldDecorator('left')(<Input placeholder="请输入" />)}
            </Form.Item>

            <Form.Item label="操作符">
              {form.getFieldDecorator('yunsuan', {
                initialValue: '等于',
              })(
                <Select allowClear>
                  <Select.Option value="等于">等于</Select.Option>
                  <Select.Option value="大于">大于</Select.Option>
                  <Select.Option value="大等于">大等于 </Select.Option>
                  <Select.Option value="小于">小于</Select.Option>
                  <Select.Option value="小等于"> 小等于 </Select.Option>
                  <Select.Option value="不等于">不等于</Select.Option>
                </Select>
              )}
            </Form.Item>

            <Form.Item label="右表达式">
              {form.getFieldDecorator('right')(<Input placeholder="请输入" />)}
            </Form.Item>

            <Form.Item>
              <a
                onClick={() => {
                  this.createParams();
                }}
              >
                + 添加生成表达式
              </a>
            </Form.Item>

            <Form.Item>
              <span>
                <span>关联条件：</span>
                <Button
                  size="small"
                  onClick={() => {
                    this.Addyunsuan('AND');
                  }}
                  className="margin-right"
                >
                  AND
                </Button>
                <Button
                  size="small"
                  onClick={() => {
                    this.Addyunsuan('OR');
                  }}
                  className="margin-right"
                >
                  OR
                </Button>
                <Button
                  size="small"
                  onClick={() => {
                    this.Addyunsuan('(');
                  }}
                  className="margin-right"
                >
                  (
                </Button>
                <Button
                  size="small"
                  onClick={() => {
                    this.Addyunsuan(')');
                  }}
                  className="margin-right"
                >
                  )
                </Button>
              </span>
            </Form.Item>
          </Fragment>
        ) : null}
        <Form.Item>
          {form.getFieldDecorator('params', {
            initialValue: params,
          })(
            <Input.TextArea
              rows={3}
              placeholder="生成表达式内容"
              onBlur={this.handleSubmit}
              disabled={operType === 'view' ? true : false}
            />
          )}
        </Form.Item>
      </Fragment>
    );
  };

  render() {
    const { formState, memberState, configState, loading, memberCheck, formView } = this.state;
    const { type, size, form } = this.props;

    return (
      <Card
        type="inner"
        size="small"
        title={upperFirst(
          type === 'node' ? '环节设置配置' : type === 'edge' ? '跃迁设置' : '流程配置信息'
        )}
        bordered={false}
      >
        <ScrollBar autoHide autoHeight autoHeightMax={size.height - 100}>
          <div style={{ margin: '0 16px' }}>
            <Spin spinning={loading}>
              <Form onSubmit={this.handleSubmit}>
                {type === 'node' && this.renderNodeDetail()}
                {type === 'edge' && this.renderEdgeDetail()}
                {type === 'canvas' && this.renderCanvasDetail()}
              </Form>
            </Spin>
          </div>
        </ScrollBar>
        {formState ? (
          <SelectForm
            visiable={formState}
            close={() => {
              this.setState({
                formState: false,
              });
            }}
            callback={this.formCallBack}
          />
        ) : null}
        {memberState ? (
          <SelectMember
            visiable={memberState}
            close={() => {
              this.setState({
                memberState: false,
              });
            }}
            callback={this.memberCallBack}
            memberCheck={memberCheck}
            operMode={form.getFieldValue('operMode')}
          />
        ) : null}
        {configState ? (
          <AddConfigRow
            visiable={configState}
            close={() => {
              this.setState({
                configState: false,
              });
            }}
            callback={this.configCallBack}
          />
        ) : null}
        {/* 表单预览 */}
        {formView ? (
          <Modal
            className={styles.modal}
            title="表单预览"
            visible={formView}
            onCancel={() => {
              this.setState({
                formView: false,
              });
            }}
            footer={null}
            width="60%"
            destroyOnClose
          >
            <ScrollBar autoHide autoHeight autoHeightMax={size.height * 0.7}>
              <div style={{ height: size.height * 0.7 }} className={styles.set_conditionright}>
                <Flow2 formId={form.getFieldValue('formId')} mode="readOnly" />
              </div>
            </ScrollBar>
          </Modal>
        ) : null}
      </Card>
    );
  }
}

export default connect(({ setting, flowConfig }) => ({
  size: setting.size,
  canvasObj: flowConfig.canvasObj,
  operType: flowConfig.operType,
}))(Form.create()(withPropsAPI(DetailForm)));
